<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="餐食名称" prop="mealName">
              <el-input v-model="queryParams.mealName" placeholder="请输入餐食名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="餐食类型" prop="mealType">
              <el-select v-model="queryParams.mealType" placeholder="请选择餐食类型" clearable style="width: 240px">
                <el-option
                  v-for="dict in sys_meat_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="老人姓名" prop="elderName">
              <el-input v-model="queryParams.elderName" placeholder="请输入老人姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleProcess" v-hasPermi="['nursing:foodService:add']">创建服务流程</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['nursing:foodService:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['nursing:foodService:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['nursing:foodService:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="foodServiceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="服务ID" align="center" prop="serviceId" v-if="true" />
        <el-table-column label="图片" align="center" prop="foodUriUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.foodUriUrl" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="餐食名称" align="center" prop="mealName" />
        <el-table-column label="餐食类型" align="center" prop="mealType">
          <template #default="scope">
            <dict-tag :options="sys_meat_type" :value="scope.row.mealType"/>
          </template>
        </el-table-column>
        <el-table-column label="用餐时间" align="center" prop="mealTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.mealTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="老人姓名" align="center" prop="elderName" />
        <el-table-column label="食物清单" align="center" prop="foodItems" />
        <el-table-column label="饮食要求" align="center" prop="dietaryRequirements" />
        <el-table-column label="过敏信息" align="center" prop="allergies" />
        <el-table-column label="进食状况" align="center" prop="eatingStatus" />
        <el-table-column label="是否需要协助" align="center" prop="assistanceNeeded">
          <template #default="scope">
            <dict-tag :options="sys_assistance_needed" :value="scope.row.assistanceNeeded"/>
          </template>
        </el-table-column>
        <el-table-column label="是否需要客房送餐" align="center" prop="isVisitingService">
          <template #default="scope">
            <dict-tag :options="sys_is_visiting_service" :value="scope.row.isVisitingService"/>
          </template>
        </el-table-column>
        <el-table-column label="房间号" align="center" prop="roomId" />
        <el-table-column label="服务人员姓名" align="center" prop="staffName" />
        <el-table-column label="备注" align="center" prop="remarks" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nursing:foodService:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nursing:foodService:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改饮食服务对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="foodServiceFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="图片" prop="foodUri">
          <image-upload v-model="form.foodUri"/>
        </el-form-item>
        <el-form-item label="餐食名称" prop="mealName">
          <el-input v-model="form.mealName" placeholder="请输入餐食名称" />
        </el-form-item>
        <el-form-item label="餐食类型" prop="mealType">
          <el-select v-model="form.mealType" placeholder="请选择餐食类型">
            <el-option
                v-for="dict in sys_meat_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用餐时间" prop="mealTime">
          <el-date-picker clearable
            v-model="form.mealTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择用餐时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="老人姓名" prop="elderName">
          <el-input v-model="form.elderName" placeholder="请输入老人姓名" />
        </el-form-item>
        <el-form-item label="食物清单" prop="foodItems">
            <el-input v-model="form.foodItems" type="textarea" placeholder="请输入食物清单" />
        </el-form-item>
        <el-form-item label="饮食要求" prop="dietaryRequirements">
          <el-input v-model="form.dietaryRequirements" placeholder="请输入饮食要求" />
        </el-form-item>
        <el-form-item label="过敏信息" prop="allergies">
          <el-input v-model="form.allergies" placeholder="请输入过敏信息" />
        </el-form-item>
        <el-form-item label="进食状况" prop="eatingStatus">
          <el-input v-model="form.eatingStatus" placeholder="请输入进食状况" />
        </el-form-item>
        <el-form-item label="是否需要协助" prop="assistanceNeeded">
          <el-select v-model="form.assistanceNeeded" placeholder="请选择是否需要协助">
            <el-option
                v-for="dict in sys_assistance_needed"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否需要客房送餐" prop="isVisitingService">
          <el-select v-model="form.isVisitingService" placeholder="请选择是否需要客房送餐">
            <el-option
                v-for="dict in sys_is_visiting_service"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间号" prop="roomId">
          <el-input v-model="form.roomId" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="服务人员姓名" prop="staffName">
          <el-input v-model="form.staffName" placeholder="请输入服务人员姓名" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="handleUpdate">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FoodService" lang="ts">
import { listFoodService, getFoodService, delFoodService, updateFoodService } from '@/api/nursing/foodService';
import { FoodServiceVO, FoodServiceQuery, FoodServiceForm } from '@/api/nursing/foodService/types';
import { useRouter } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const { sys_assistance_needed, sys_is_visiting_service, sys_meat_type } = toRefs<any>(proxy?.useDict('sys_assistance_needed', 'sys_is_visiting_service', 'sys_meat_type'));

const foodServiceList = ref<FoodServiceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const foodServiceFormRef = ref<ElFormInstance>();

/** 查询参数 */
const queryParams = ref<FoodServiceQuery>({
  pageNum: 1,
  pageSize: 10,
  elderName: '',
  mealName: '',
  mealType: '',
  status: '',
  params: {}
});

/** 表单参数 */
const form = ref<FoodServiceForm>({});

/** 弹出层标题 */
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

/** 表单校验规则 */
const rules = reactive({
  mealName: [
    { required: true, message: "餐食名称不能为空", trigger: "blur" }
  ],
  elderName: [
    { required: true, message: "老人姓名不能为空", trigger: "blur" }
  ]
});

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listFoodService(queryParams.value);
    foodServiceList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = {};
  queryFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: FoodServiceVO[]) => {
  ids.value = selection.map(item => item.serviceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 修改按钮操作 */
const handleUpdate = async (rowOrEvent?: FoodServiceVO | MouseEvent) => {
  if (rowOrEvent && !(rowOrEvent instanceof MouseEvent)) {
    const res = await getFoodService(rowOrEvent.serviceId);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改饮食服务";
  } else {
    try {
      await foodServiceFormRef.value?.validate();
      buttonLoading.value = true;
      await updateFoodService(form.value);
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    } catch (error) {
      console.error('表单验证失败:', error);
    } finally {
      buttonLoading.value = false;
    }
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: FoodServiceVO) => {
  const _serviceIds = row?.serviceId || ids.value;
  await proxy?.$modal.confirm('是否确认删除饮食服务编号为"' + _serviceIds + '"的数据项？').finally(() => loading.value = false);
  await delFoodService(_serviceIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('nursing/foodService/export', {
    ...queryParams.value
  }, `foodService_${new Date().getTime()}.xlsx`);
};

/** 创建服务流程按钮操作 */
const handleProcess = () => {
  router.push('/nursing/foodServiceProcess');
};

onMounted(() => {
  getList();
});
</script>
